﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Mbs.Modularity.AddIns;
using Mbs.Reflection;
using Mbs.MessageService;

namespace Mbs.Modularity
{
    [Serializable]
    internal class ConfigurationModuleActivatorProcessor: MarshalByRefObject, IModuleActivatorProcessor
    {
        private List<IModuleActivatorProcessor> processores;
        private IEnumerable<IExtensionPoint> ExtensionPoints;

        public ConfigurationModuleActivatorProcessor(IModuleMeta meta)
        {
            Init(meta);
        }

        private void Init(IModuleMeta meta)
        {
            ExtensionPoints = meta.AddIn.Runtime.ExtensionPoints;
            processores = new List<IModuleActivatorProcessor>();
            var classLoader = ServiceLocator.Current.Get<IClassLoader>();

            foreach (var ep in ExtensionPoints)
            {
                var obj = classLoader.NewInstance<IModuleActivator>(ep.Value);
                var processor = new ModuleActivatorProcessor(obj,ep.IsAsyn, meta);

                processores.Add(processor);
            }
        }

        

        public void Process()
        {

            if (ExtensionPoints == null || ExtensionPoints.Count() <= 0)
            {
                //MsgBox.ShowError("No activator found");
                return;
            }

            foreach (var item in processores)
                item.Process();
            
        }

        public void Dispose()
        {
            foreach (var item in processores)
               if (item != null)
                   item.Dispose();
            processores.Clear();
        }
    }
}
